package com.wny.server;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Li 
 * Supply the core methods to connect with / close database directly.
 * These methods are to be invoked by high-level class
 */

public class DBConnector {

	private Connection dbConn = null;

	private String driverName;
	private String dbHost;
	private String dbPort;
	private String dbName;
	private String dbUserName;
	private String dbPassword;
	// private String enCoding;

	/**
	 * Instantiate DbConn object
	 * 
	 * @param host
	 *            DataBase Host
	 * @param port
	 *            DataBase Port
	 * @param dName
	 *            DataBase name
	 * @param uName
	 *            user name
	 * @param pwd
	 *            password
	 * 
	 */

	public DBConnector(String host, String port, String dName, String uName,
			String pwd) {
		driverName = "com.mysql.jdbc.Driver";
		dbHost = host;
		dbPort = port;
		dbName = dName;
		dbUserName = uName;
		dbPassword = pwd;
		// enCoding = "";
	}

	/**
	 * Establish connection
	 * 
	 * @return true for success, false for failure
	 */
	public Connection getdbConnection() {
		
		StringBuilder urlTem = new StringBuilder();
		urlTem.append("jdbc:mysql://");
		urlTem.append(dbHost);
		urlTem.append(":");
		urlTem.append(dbPort);
		urlTem.append("/");
		urlTem.append(dbName);
		// urlTem.append(enCoding);
		
		String url = urlTem.toString();
		try {
			Class.forName(driverName).newInstance();
			dbConn = DriverManager.getConnection(url, dbUserName, dbPassword);
			return dbConn;
		} catch (Exception ex) {
			System.out.println("Fail to connect database");
			System.out.println("URL = " + url);
			ex.printStackTrace();
			return null;
		}
	}// end dbConnection()
	
	/**
	 * Close Database Connection
	 * 
	 * @return true for success, false for failure
	 */
	public boolean dbClose() {
		try {
			if (dbConn != null)
				dbConn.close();
			return true;
		} catch (SQLException ex) {
			ex.printStackTrace();
			return false;
		}
	}// end dbClose()
}